package com.iqiyi.dbagent;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.iqiyi.dbagent.base.config.CommParme.INPUTTYPR;
import com.iqiyi.dbagent.base.config.MySqlConfig;
import com.iqiyi.dbagent.base.config.i.Configuration;
import com.iqiyi.dbagent.base.i.ISqlMonitorServer;
import com.iqiyi.dbagent.base.utils.data.DataSourceUtil;
import com.iqiyi.dbagent.base.utils.time.DateUtil;
import com.iqiyi.dbagent.contraller.StreamDataContraller;
import com.iqiyi.dbagent.contraller.i.DBAgentTemplate;
import com.iqiyi.dbagent.contraller.i.IDataContraller;
import com.iqiyi.dbagent.contraller.i.IDataStoreHandler;
import com.iqiyi.dbagent.contraller.impl.DataTransStoreHandler;
import com.iqiyi.dbagent.contraller.impl.MysqlAgentTemplate;
import com.iqiyi.dbagent.view.web.SqlMonitorServer;

/**
*
* @Title: App4QiYiDB.java
* @Package com.iqiyi.dbagent
* @Description: 支持入库(
* 1,innodb类型的事务操作:
* 2,支持指定字段值(数值类型),增量,减量,更新,直接入库的细化操作;
* 3,可指定操作哪些时间的数据;
* 4,可选择是否使用事务)
* @author wangnianming
* @date 2016年1月3日 下午4:49:43
* @version V1.0
*/
public class App4QiYiDB extends HttpServlet {

	/** 日志记录器 */
	private final static Logger logger = LoggerFactory.getLogger(App4QiYiDB.class);

	private static final long serialVersionUID = 1L;
	
	private DataSourceUtil dataSourceOperator;

	public static void main(String[] args) {
        ArgumentParser parser = ArgumentParsers.newArgumentParser("dbAgent");
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        parser.defaultHelp(true);
        parser.description("Import data to DB, including Mysql and Mongo....");
        parser.epilog("dbAgent");
        parser.addArgument("-itype", "--inputtype").choices("insert","increase", "reduce", "update").setDefault("update").help("Specify data into db function to use");
        parser.addArgument("--transaction").action(Arguments.storeFalse()).help("Update DB in transaction mode");
        parser.addArgument("--monitor").action(Arguments.storeFalse()).help("if use web monitor sql");
        parser.addArgument("-iport", "--monitorport").setDefault(8090).help("Monitor web port,not use sys_port to use,then u can accsee:"+"http://"+addr.toString()+":uport/dbAgent/druid");
        parser.addArgument("idaytime").nargs("*").help("data at this time(point or range or time list) whill into db");
        //parser.addArgument("--initonly").action(Arguments.storeFalse()).help("only init db");
        //parser.addArgument("-busitp", "--businesstype").choices("kadun","vcdn", "scdn", "disp").setDefault("default").help("Specify business data to deal");
        logger.info(parser.formatUsage());
		Namespace ns = null;
        try {
            ns = parser.parseArgs(args);
        } catch (ArgumentParserException e) {
            parser.handleError(e);
            String alarmCause = e.getMessage();
            logger.error("parse argument error{}",alarmCause);
        }

        Configuration config = new MySqlConfig("config.properties");

        if ((null!=ns && null!=ns.getBoolean("transaction")) && !ns.getBoolean("transaction")) {
            logger.info("use transaction has been on");
            config.setUseTransaction(true);
        }else{
            logger.info("use transaction has been off");
            config.setUseTransaction(false);
        }
        if((null!=ns && null!=ns.getString("inputtype")) && !"".equals(ns.getString("inputtype").trim())) {
            config.setInputType(INPUTTYPR.valueOf(ns.getString("inputtype").toUpperCase()));
        }else{
            config.setInputType(INPUTTYPR.valueOf("increase".toUpperCase()));
        }
        if((null!=ns && null!=ns.getString("idaytime")) && !"".equals(ns.getString("idaytime").trim())){
            for (String timeStr : ns.<String> getList("idaytime")) {
                Date dataDate = DateUtil.parseDateTime(timeStr);
                logger.info("dateTime:{}",dataDate);
            }
        }

        DBAgentTemplate template = new MysqlAgentTemplate();

        IDataStoreHandler handler = new DataTransStoreHandler();

        IDataContraller contraller = new StreamDataContraller(System.in,handler);

        ISqlMonitorServer server = null;

        if ((null!=ns && null!=ns.getBoolean("monitor")) && !ns.getBoolean("monitor")) {
            logger.info("use sqlmonitor has been on:{}",ns.getString("monitorport"));
            server = new SqlMonitorServer(new Server(),Integer.parseInt(ns.getString("monitorport")));
            server.startMonitor();
        }

        contraller.dealData(config, template,server);

    }

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        logger.info("初始化web上下文:{}",ctx);
        dataSourceOperator = (DataSourceUtil) ctx.getBean("dbAgentDataUtilBean");
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        request.getSession().setAttribute("username", "myname");
        boolean createResult = false;
        boolean insertResult = false;
        boolean dropResult = false;
        out.println("{'createResult':" + createResult + ",'insertResult':"
                + insertResult + ",'dropResult':" + dropResult + "}");
        out.flush();
        out.close();
    }

    public DataSourceUtil getDataSourceOperator() {
        return dataSourceOperator;
    }

    public void setDataSourceOperator(DataSourceUtil dataSourceOperator) {
        this.dataSourceOperator = dataSourceOperator;
    }
}
